package com.suwish.pc.ui.component.tab;

import static com.suwish.pc.util.ResourceUtils._Icon;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;

import com.suwish.device.util.Platform;
import com.suwish.pc.Setting;
import com.suwish.pc.util.StringUtils;

/**
 * 
 * @author Min
 *
 */
public class UITabbedPanel extends JPanel  implements MouseListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
//	private static UITabContainer instance = null;
	
	private JPanel tabs = null;
	private JPanel mainPanel = null;
	
	public static final Cursor DEFAULT_CURSOR = new Cursor(Cursor.DEFAULT_CURSOR);
	public static final Cursor HAND_CURSOR = new Cursor(Cursor.HAND_CURSOR);
	
	//关闭按钮的失去焦点时的图标
    private Icon closeInactiveButtonIcon;
    //关闭按钮获得焦点的图标
    private Icon closeActiveButtonIcon;
	
    private ImageIcon backgroudImage = null;
    
	public UITabbedPanel(){
		initUI();
	}
	
//	public static synchronized UITabContainer getInstance(){
//		return instance == null ? instance = new UITabContainer() : instance;
//	}
	
	
	public boolean isDeviceTabExits(String serialNumber){
		
		return isTabExits(serialNumber);
	}
	
	public boolean isTabExits(String tabName){
		if(StringUtils.isEmpty(tabName)) return false;
		int count =	getTabCount();
		for(int index = 0 ; index < count ; index ++){
			Component c = getComponentAt(index);
			if(!(c instanceof UITabbedPanel)) continue;
			if(tabName.equals(((UITabPanel)c).getName())) return true;
		}
		return false;
	}
	public int getTabIndex(String tabName){
		if(StringUtils.isEmpty(tabName)) return -1;
		int count =	getTabCount();
		for(int index = 0 ; index < count ; index ++){
			Component c = getComponentAt(index);
			if(!(c instanceof UITabPanel)) continue;
			if(tabName.equals(((UITabPanel)c).getName())) return index;
		}
		return -1;
	}
	public UITab addContainerComponent(UITabPanel tabPanel){
		return addTab(tabPanel.getIcon(), tabPanel.getTitle(), tabPanel, tabPanel.getTip());
	}

	public UITab addTab(Icon icon, String text, final UITabPanel tabPanel, String toolTip){
		UITab tab = addTab(icon, text, tabPanel);
		if(tab != null)
		tab.setToolTipText(toolTip);
		return tab;
	}
	
	public UITab addTab(Icon icon, String text, final UITabPanel tabPanel){
		int index = getTabIndex(tabPanel.getName());
		if(index != -1){
			setSelectedIndex(index);
			return null;
		}
		final UITab tab = new UITab(icon, text);
		tabs.add(tab, new GridBagConstraints(tabs.getComponentCount(), 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
		tab.addMouseListener(this);
        //tabs.add(tab);
        // Add Component to main panel
        mainPanel.add(Integer.toString(tabPanel.hashCode()), tabPanel);
        
        if (getSelectedIndex() == -1) {
            setSelectedTab(tab);
        }
        final JLabel closeButton = new JLabel(closeInactiveButtonIcon);
        tab.addComponent(closeButton);
        closeButton.addMouseListener(new MouseAdapter()  {
                    public void mouseEntered(MouseEvent mouseEvent) {
                        if (Platform.isWindows()) {
                            closeButton.setIcon(closeActiveButtonIcon);
                        }

                        setCursor(HAND_CURSOR);
                    }

                    public void mouseExited(MouseEvent mouseEvent) {
                        if (Platform.isWindows()) {
                            closeButton.setIcon(closeInactiveButtonIcon);
                        }

                        setCursor(DEFAULT_CURSOR);
                    }

                    public void mousePressed(MouseEvent mouseEvent) {
                    	close(tab, tabPanel);
                    }
        });
		return tab;
	}
	
	private void initUI(){
		setLayout(new BorderLayout());
        //选项卡面板定义
        tabs = new JPanel(new FlowLayout(FlowLayout.LEFT,0,0)) {
			private static final long serialVersionUID = 1L;
					public Dimension getPreferredSize() {
                        if (getParent() == null)
                            return getPreferredSize();
                        // calculate the preferred size based on the flow of components
                        FlowLayout flow = (FlowLayout)getLayout();
                        int w = getParent().getWidth();
                        int h = flow.getVgap();
                        int x = flow.getHgap();
                        int rowH = 0;
                        Dimension d;
                        Component[] comps = getComponents();
                        for (Component comp : comps) {
                            if (comp.isVisible()) {
                                d = comp.getPreferredSize();
                                if (x + d.width > w && x > flow.getHgap()) {
                                    x = flow.getHgap();
                                    h += rowH;
                                    rowH = 0;
                                    h += flow.getVgap();
                                }
                                rowH = Math.max(d.height, rowH);
                                x += d.width + flow.getHgap();
                            }
                        }
                        h += rowH;
                        return new Dimension(w, h);
                    }
                };
                add(tabs, BorderLayout.NORTH);
                mainPanel = new JPanel(new CardLayout()){
					private static final long serialVersionUID = 1L;
					public void paintComponent(Graphics g) {
                		super.paintComponent(g);
                		if(backgroudImage == null) return;
                		g.drawImage(backgroudImage.getImage(), 
                				(getWidth() - backgroudImage.getIconWidth())/2, 
                				(getHeight() - backgroudImage.getIconHeight())/2,
                				this);
                	}
                };
                mainPanel.setToolTipText("⑨");
                mainPanel.setBackground(Color.WHITE);
                add(mainPanel, BorderLayout.CENTER);
                
                closeInactiveButtonIcon = _Icon(Setting.get("main.tab.icon.normal"));
                //关闭按钮获得焦点的图标
                closeActiveButtonIcon = _Icon(Setting.get("main.tab.icon.active"));
                backgroudImage = _Icon(Setting.get("main.tab.bg"));
	}
	
	public int getSelectedIndex() {
        Component[] comps = tabs.getComponents();
        for (int i = 0; i < comps.length; i++) {
            Component c = comps[i];
            UITab tab = (UITab)c;
            if (tab.isSelected()) {
                return i;
            }
        }

        return -1;
    }

    public void setSelectedIndex(int index) {
        Component[] comps = tabs.getComponents();
        if (index <= comps.length) {
        	UITab tab = (UITab)comps[index];
        	setSelectedTab(tab);
        }
    }

    public int getTabCount() {
        return tabs.getComponents().length;
    }

    public int indexOfComponent(Component comp) {
        Component[] comps = mainPanel.getComponents();
        for (int i = 0; i < comps.length; i++) {
            Component c = comps[i];
            if (c == comp) {
                return i;
            }
        }

        return -1;
    }

    public Component getComponentAt(int index) {
        Component[] comps = mainPanel.getComponents();
        for (int i = 0; i < comps.length; i++) {
            Component c = comps[i];
            if (i == index) {
                return c;
            }
        }

        return null;
    }

    public void removeTabAt(int index) {
    	UITab tab = getTabAt(index);
        Component comp = getComponentAt(index);
        close(tab, comp);
    }


    public UITab getTabAt(int index) {
        Component[] comps = tabs.getComponents();
        for (int i = 0; i < comps.length; i++) {
            Component c = comps[i];
            if (i == index) {
                return (UITab)c;
            }
        }

        return null;
    }

    public Component getComponentInTab(UITab tab) {
        Component[] comps = tabs.getComponents();
        for (int i = 0; i < comps.length; i++) {
            Component c = comps[i];
            if (c == tab) {
                return getComponentAt(i);
            }
        }

        return null;
    }

    public UITab getTabContainingComponent(Component comp) {
        int index = indexOfComponent(comp);
        if (index != -1) {
            return getTabAt(index);
        }

        return null;
    }

    public void removeComponent(Component comp) {
        int index = indexOfComponent(comp);
        if (index != -1) {
            removeTabAt(index);
        }
    }

    public int getIndex(UITab tab) {
        Component[] comps = tabs.getComponents();
        for (int i = 0; i < comps.length; i++) {
            Component c = comps[i];
            if (c instanceof UITab && c == tab) {
                return i;
            }
        }

        return -1;
    }
    public void setSelectedTab(UITab tab) {
        CardLayout cl = (CardLayout)mainPanel.getLayout();
        Component comp = getComponentInTab(tab);
        cl.show(mainPanel, Integer.toString(comp.hashCode()));
//        tab.setBoldWhenActive(isActiveButtonBold());

        deselectAllTabsExcept(tab);

        tab.setSelected(true);
//        fireTabSelected(tab, getSelectedComponent(), getIndex(tab));
    }
    public void close(UITab tab, Component comp) {
    	if(!(comp instanceof UITabPanel)) return;
    	UITabPanel panel = (UITabPanel)comp;
//        boolean canClose = fireTabClosing(tab, comp);
        if (!panel.close()) {
            // Cancel closing of tab.
            return;
        }

        int index = getIndex(tab);

        // Close Tab
        mainPanel.remove(comp);
        tabs.remove(tab);
        tabs.removeMouseListener(this);

        tabs.invalidate();
        tabs.validate();
        tabs.repaint();

        mainPanel.invalidate();
        mainPanel.validate();
        mainPanel.repaint();

//        fireTabRemoved(tab, comp, index);
//        Component[] comps = tabs.getComponents();
//        if (comps.length == 0) {
//            allTabsClosed();
//        }
//        else {
//            findSelectedTab(index);
//        }
    }
    
    /** ****/
    private void deselectAllTabsExcept(UITab tab) {
        Component[] comps = tabs.getComponents();
        for (int i = 0; i < comps.length; i++) {
            Component c = comps[i];
            if (c instanceof UITab) {
            	UITab comp = (UITab)c;
                if (comp != tab) {
                	comp.setSelected(false);
                }
                else {
                    int j = i - 1;
                    if (j >= 0) {
                    	UITab previousTab = (UITab)comps[j];
//                        previousTab.showBorder(false);
                    }
                }
            }

        }

    }

    public Component getSelectedComponent() {
        Component[] comps = mainPanel.getComponents();
        for (Component c : comps) {
            if (c.isShowing()) {
                return c;
            }
        }

        return null;
    }


    public Dimension getPreferredSize() {
        final Dimension size = super.getPreferredSize();
        size.width = 0;
        return size;
    }
	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent e) {
		if (e.getButton() != MouseEvent.BUTTON1) {
            dispatchEvent(e);
            return;
        }
        if (e.getSource() instanceof UITab) {
        	UITab tab = (UITab)e.getSource();
            setSelectedTab(tab);
        }
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}
}
